import FormCodegenProjectEdit3File from "./FormCodegenProjectEdit3File";
import FormCodegenFileTemplateDialog from "../FormCodegenFileTemplateDialog";
import FormCodegenFilePathApi from "@/api/form/codegen/formCodegenFilePath";
import FormCodegenVariableApi from "@/api/form/codegen/formCodegenVariable";
import {RxMonacoEditor, RxVueTree, Util} from "@lowcode/jpaas-common-lib";

export default {
    props: ["formData"],
    components: {
        RxVueTree,
        RxMonacoEditor
    },
    data() {
        return {
            settingJson: {},
            variableProjectAry:[
                {label:this.i18n('projectVar','项目变量名'),value:"projectVar"},
                {label:this.i18n('projectKey','项目别名'),value:"projectKey"},
                {label:this.i18n('projectName','项目名称'),value:"projectName"},
                {label:this.i18n('port','端口号'),value:"port"}
            ],
            variableGlobalAry:[],
            variableCustomAry:[],
            expandedKeys:[],
            dataSource:[],
            treeData:[],
            treeIcon:{
                expand:'folder-open',
                collapse:'folder',
                leaf:'file'
            },
            curTree:null,
            content:""
        }
    },
    created() {
        this.init();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formCodegenProject.edit3",key);
        },
        init() {
            var self=this;
            self.initGlobalAry();
            this.settingJson = JSON.parse(this.formData.settingJson);
            if(this.settingJson.hasOwnProperty("customVars") && this.settingJson.customVars.length>0){
                this.variableCustomAry=Util.deepClone(this.settingJson.customVars).map(item=>{
                    return {label:item.desc || item.name,value:item.name};
                });
            }
            if(this.settingJson.hasOwnProperty("files") && this.settingJson.files.length>0){
                self.dataSource=self.settingJson.files;
                let ary=Util.treeData(self.settingJson.files,"id","parentId","children","-1");
                self.treeData = [...ary];
            }else{
                self.treeData.push({id:"0",name:this.formData.key,path:"",parentId:"-1",children:[]});
            }
            self.expandedKeys.push("0");
        },
        selectTemplate(){
            var self=this;
            if(this.treeData[0].children && this.treeData[0].children.length>0) {
                this.$confirm({
                    title: this.$ti18('rxMsa.tipsInfo','提示信息'),
                    content: this.i18n('msg.ovrrideTip','已经配置了文件，选择后会覆盖，是否确认？'),
                    okText: this.$ti18('rxForm.ackBtn','确认'),
                    zIndex: 10000,
                    cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    onOk() {
                        self.openTemplateDialog();
                    },
                    onCancel() {
                    }
                })
            }else{
                self.openTemplateDialog();
            }
        },
        openTemplateDialog(){
            var self=this;
            var config = {
                curVm: this,
                component: FormCodegenFileTemplateDialog,
                title: this.i18n('title','选择模板文件配置'),
                widthHeight:['800px','600px'],
            };
            Util.open(config, function (action,row) {
                if(action!="ok"){
                    return;
                }
                FormCodegenFilePathApi.queryList({params:{"Q_DELETED__I_EQ":"0","Q_TEMPLATE_ID__S_EQ":row.id},sortField:"TYPE_",sortOrder:"ASC"}).then(res=>{
                    if(res.success){
                        self.dataSource=res.data;
                        let ary=Util.treeData(res.data,"id","parentId");
                        let data =Util.deepClone(self.treeData);
                        data[0].children = ary ;
                        self.treeData = [...data];
                        self.curTree=null;
                    }
                })
            })
        },
        getData(){
            let fileData=[];
            this.treeToList(Util.deepClone(this.treeData),fileData);
            let data={files:fileData};
            let result={success:true,data:data};
            if(fileData.length==1){
                result.success=false;
                result.message=this.this.i18n('msg.noConfigFile','请配置至少一个文件！');
                return result;
            }
            return result;
        },
        treeToList(treeData,listData){
            for(let i=0;i<treeData.length;i++){
                let tree=treeData[i];
                if(tree.children && tree.children.length>0){
                    this.treeToList(tree.children,listData);
                }
                delete tree.children;
                listData.push(tree);
            }
        },
        initGlobalAry(){
            var self=this;
            FormCodegenVariableApi.queryList({params:{"Q_ENABLED__S_EQ":"YES"}}).then(res=>{
                if(!res || !res.data){
                    return;
                }
                self.variableGlobalAry=res.data.map(item=>{
                    return {value:item.name,label:item.desc};
                });
            })
        },
        insertScript(item,alias){
            var script="${"+alias+"."+item.value+"}";
            this.$refs.content.insertContent(script);
        },
        handSelect(tree) {
            if(tree.type!="file" || (this.curTree && this.curTree.id==tree.id)){
                return;
            }
            var self=this;
            //切换文件,自动保存
            this.saveContent(function(){
                self.curTree=tree;
                self.content=tree.content || "";
            });
        },
        btnSaveContent(){
            this.saveContent();
            this.$message.info(this.i18n('msg.saveSuccess','文件内容保存成功！'));
        },
        saveContent(callback) {
            if (callback) {
                if (!this.curTree ||
                    this.curTree.content == this.content) {
                    callback();
                    return;
                }
            }
            if(this.curTree) {
                this.curTree.content = this.content;
            }
            if (callback) {
                callback();
                this.$message.info(this.i18n('msg.autoSave','文件内容自动保存！'));
            }
        },
        collapseAll() {
            this.expandedKeys.length=0;
            this.expandedKeys.push("0");
        },
        expandAll() {
            this.expandedKeys.length=0;
            this.expandedKeys.push("0");
            for (var i = 0; i < this.dataSource.length; i++) {
                this.expandedKeys.push(this.dataSource[i]["id"])
            }
        },
        addNode(tree,type) {
            let data = {
                type:type,
                parentId:tree.id,
                parentPath:tree.path
            }
            let name=this.getByName(type);
            this.handClick(data, this.$ti18('rxList.newBtn','添加')+name, "addChild",tree);
        },
        editNode(tree) {
            let {type}=tree;
            let name=this.getByName(type);
            this.handClick(tree, this.$ti18('rxList.editBtn','编辑')+name, "edit");
        },
        handClick(data, title, operator,parentData) {
            var conf = {
                curVm: this,
                data: {data: data,globarAry:this.variableGlobalAry,customAry:this.variableCustomAry},
                widthHeight: ['600px', '200px'],
                component: FormCodegenProjectEdit3File,
                title: title,
                maxmin:false
            };
            let self_ = this;
            Util.open(conf, async function (action) {
                if (action != "ok") {
                    return;
                }
                let row = this.resultData;
                switch (operator) {
                    case "edit":
                        data.name=row.name;
                        self_.treeData = [...self_.treeData];
                        break;
                    case "addChild":
                        if(parentData.hasOwnProperty('children') && Object.prototype.toString.call(parentData.children).indexOf('Array')>-1){
                            parentData.children.push(row)
                        }else {
                            parentData['children'] = [row];
                        }
                        self_.treeData = [...self_.treeData];
                        break;
                }
            });
        },
        getByName(type){
            let name="";
            if(type=="file") {
                name = this.i18n('file','文件');
            }else if(type=="directory") {
                name = this.i18n('directory','目录')
            }
            return name;
        },
        deleteNode(tree,parentData) {
            var {id,type} = tree;
            let name=this.getByName(type);
            let self_ = this;
            this.$confirm({
                title: this.$ti18('rxMsa.tipsInfo','提示信息'),
                content: this.i18n('msg.deleteTip','您确定需要删除选中的')+name+'？',
                okText: this.$ti18('rxForm.ackBtn','确认'),
                cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                zIndex:99999,
                onOk() {
                    let index =  parentData.children.findIndex(obj=>obj.id == tree.id);
                    parentData.children.splice(index,1);
                },
                onCancel() {
                }
            })
        }
    }
}